from django.shortcuts import render
from django.http import HttpRequest, HttpResponse, JsonResponse
from django.views import View

from book.models import BookInfo
import json
# Create your views here.


def index(request: HttpRequest):
    return HttpResponse("ok")


def register(request: HttpRequest):
    print("call register: ")
    print(request.POST)
    return HttpResponse("register succeed!")

def json_test(request: HttpRequest):

    body_str = request.body.decode()
    # 这里获取的是字符串. json形式的字符串. 可以转换成python的字典.
    print(body_str)
    body_dict = json.loads(body_str)
    print(body_dict)
    print(request.META['SERVER_PORT'])
    return HttpResponse("json!")

def create_book(request):
    book = BookInfo.objects.create(
        name='abc',
        pub_date='2010-10-10',
    )
    return HttpResponse("create")


def shop(request, city_id, shop_id):

    import re
    if not re.match('\d{5}', shop_id):
        return HttpResponse("无效商品id")


    query_params = request.GET
    print(query_params) # 类型是QueryDict
    order = query_params.get("order") # 方式一.
    order = query_params['order'] # 方式二
    return HttpResponse(f"你的订单号是:{order}")
    #return HttpResponse(f"city_id:{city_id}城市 shopid:{shop_id} 商店")


def login(request, mobile):
    return HttpResponse(f"你输入的手机号是:{mobile}")


"""
第一次请求， 携带查询字符串.
服务器接受到请求之后，获取username, 服务器设置cookie数据， 信息爆火username.
http://127.0.0.1:8000/book/set_cookie/?username=itcast&password=123
浏览器接受到服务器的响应后，把cookie保存起来
"""


def set_cookie(request):
    # 1. 获取查询字符串
    username = request.GET.get('username')
    # 2. 服务器设置cookie信息
    response = HttpResponse("set_cookie")

    response.set_cookie('name', username)

    return response


def get_cookie(request):

    # 获取cookie.
    print(request.COOKIES)
    name = request.COOKIES.get('name')
    return HttpResponse(name)


def set_session(request):
    """
    第一次请求，服务器生成一个session, 并设置道cookie中.
    第二次请求， 客户端带session. 服务器验证， 并读取相关数据.
    """
    # 获取cookie.
    # 1. 模拟，获取username.
    # 2. 设置session信息.
    user_id = 1
    username = request.GET.get('username')
    request.session['user_id'] = user_id
    request.session['username'] = username
    # 3.

    return HttpResponse("set_session")


def get_session(request):
    # 会抛异常.
    # user_id = request.session['user_id']
    # user_name = request.session['username']

    user_id = request.session.get('user_id')
    user_name = request.session.get('username')
    content = '{}-{}'.format(user_id, user_name)
    return HttpResponse(content)


"""
类视图的定义
class 类视图名字(View):
    def get(self, request):
        return HttpResponse('get')
    def post(self, request):
        return HttpResponse('get')
1. 继承自 View.
2. 实现对应请求方法的方法.
"""


from django.contrib.auth.mixins import LoginRequiredMixin

# LoginRequiredMixin 作用: 判断 只有登录用户才可以访问页面.
class LoginView(View):
    def get(self, request):
        return HttpResponse('LoginView get')

    def post(self, request):
        body_dict = json.loads(request.body.decode())

        username = body_dict.get('username')
        password = body_dict.get('password')
        data = {
            "code": 200,
            "username": username,
            "password": password,
            "msg": "登录正确",
        }
        info = f"账号:{username} 密码：{password}"
        print(info)
        return JsonResponse(data)
